package wx

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
)

type PhoneInfo struct {
	PhoneNumber     string    `json:"phoneNumber"`
	PurePhoneNumber string    `json:"purePhoneNumber"`
	CountryCode     string    `json:"countryCode"`
	Watermark       Watermark `json:"watermark"`
}

type PhoneNumberResponse struct {
	ErrCode   int64     `json:"errCode"`
	ErrMsg    string    `json:"errMsg"`
	PhoneInfo PhoneInfo `json:"phone_info"`
}

func GetPhoneNumber(accessToken string, code string) (*PhoneNumberResponse, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken)
	body := struct {
		Code string `json:"code"`
	}{
		Code: code,
	}

	data, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}

	resp, err := http.Post(url, "application/json", bytes.NewReader(data))
	if err != nil {
		return nil, err
	}

	defer func() {
		_ = resp.Body.Close()
	}()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	logx.Infof(string(respBody))
	var p PhoneNumberResponse
	err = json.Unmarshal(respBody, &p)
	if err != nil {
		return nil, err
	}

	return &p, nil
}
